//跟进计划列表
var $taxDiscFromTable = $('#taxDiscFrom');
var abs = new verjs_select();
//防止表头与表格不对齐
$(window).resize(function () {
    $taxDiscFromTable.bootstrapTable('resetView');
});

$(function () {

    //初始化列表
    taxDiscFromList();
    //加载公司列表
    loadCompanySelect();
    loadCompanyTaxSelect();
    // 初始化下拉菜单(赠品除外)
    $('form select:not("#useCompanyId2")').selectpicker({
        // liveSearch: false,
        sanitize: true,
        size: 10,
    });
    getCompanyTax();
    $('#searchCompanySelect').on('change', function () {
        getCompanyTaxNumber($('#searchCompanySelect').val());
    })
})

function taxDiscFromList() {
//先销毁表格
    $taxDiscFromTable.bootstrapTable('destroy');
    $taxDiscFromTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/companyInvoice/getCompanyList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: false,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title:'',field:'useCompanyIds',visible: false},
            {title: '公司名称',field: 'companyName', align: 'left', valign: 'middle'},
            {title: '主税盘号',field: 'taxNumber', align: 'left', valign: 'middle'},
            {title: '从税盘号', field: 'useTaxNumbers', align: 'left', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'right',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#taxDiscFrom').css({
                minWidth: $('#taxDiscFrom').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,5],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}


function searchOrderList(type) {
    $('.all').addClass('active-second');
    $('.today').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    if (type === 1) {//普通条件查询
        $taxDiscFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams2});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $taxDiscFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName2').val());//客户名称
    params.userName = $.trim($('#userName').val());//原所属人名称
    params.startDate = $.trim($('#startDate').val());//开始计划日期
    params.companyId = $.trim($('#searchCompanySelect').val());
    params.endDate = $.trim($('#endDate').val());//截止计划日期
    params.dateType = $('#dateType').val();
    return params;
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.companyName = $.trim($('#companyName').val());//客户名称
    return params;
}

function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 加载公司下拉列表
 */
function loadCompanySelect() {
    $.getJSON("/sysCompany/selectCompanies", function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            var optionArr = data.data;
            var optionSelected = $('#companySelect option:selected').val();
            //公司搜索条件下拉框
            var searchCompanyOptionHtml = '<option onclick="changeName('+0+');" value="">全部</option>';
            optionArr.map(function (item, index) {
                searchCompanyOptionHtml += '<option onclick="changeName('+item.companyId+');" value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#searchCompanySelect').html(searchCompanyOptionHtml);
            var selectDate = [];
            for (var i = 0, len = data.data.length; i < len; i++) {
                var company = data.data[i];
                var selectCompany = {};
                selectCompany.id = company.companyId;
                selectCompany.name = company.companyName;
                selectDate.push(selectCompany);
            }
            /*abs.render({
                elem: "#search",
                data: selectDate,
                init_value: [1],
                body_height: 300,
                checkbox: true,
                name: "test"
            });*/
            $('#searchoption-list').css('z-index',1000);
            $('#searchCompanySelect').selectpicker({
                sanitize: true,
                size: 8
            });
        }
    });
}

function changeName(companyId) {
    console.info("companyId  "+companyId);
}

/**
 * 加载公司下拉列表
 */
function loadCompanyTaxSelect() {


    $.ajax({
        ///sysCompany/selectCompanyAndTaxNumberList
        url: "/sysInvoiceCompany/selectInvoiceCompanyList",
        type:"post",
        dataType: 'json',
        async:false,
        // contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            var data = data.data;

            var productListHtml = '';
            for (var i = 0; i < data.length; i++) {
                productListHtml += '<option value="' + data[i].companyId + '">' + data[i].companyName+'-'+ data[i].taxNumber + '</option>'
            }

            //$('#productList').html('<option value="1">全部产品</option>' + productListHtml).selectpicker('refresh');
            $('#useCompanyId').html(productListHtml).multiselect("destroy").multiselect({
                filterPlaceholder: '搜索',
                enableFiltering: true,
                includeSelectAllOption: false,
                maxHeight: 300,
                selectAllText: '全部选择',
                nonSelectedText: '请选择',
                nSelectedText: '已选择',
                allSelectedText: '已选择全部',
                buttonWidth: '100%',
                buttonText: function(options, select) {
                    console.log(options.length, select);

                    if (options.length === 0) {
                        return '请选择公司';
                    } else {
                        return '已选择' + options.length + '个公司';
                    }
                },
                onChange: function () {

                },
                onSelectAll: function () {
                    return '已选择全部'
                },
                onDeselectAll: function () {

                }
            });
        },
        error: function (err) {
            console.log(err);
        }
    })
}

/**
 * 加载公司下拉列表
 */
function loadCompanyTaxSelect2(useTaxNumbers) {
    ///sysCompany/selectCompanyAndTaxNumberList /sysInvoiceCompany/selectInvoiceCompanyList
    $.getJSON("/sysInvoiceCompany/selectInvoiceCompanyList", function (data) {
        if (data.code == '000000') {
            var data = data.data;

            var productListHtml = '';
            for (var i = 0; i < data.length; i++) {
                productListHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>'
            }
            $('#giftList').html(productListHtml).multiselect("destroy").multiselect({
                filterPlaceholder: '搜索',
                enableFiltering: true,
                includeSelectAllOption: false,
                maxHeight: 300,
                selectAllText: '全部选择',
                nonSelectedText: '请选择',
                nSelectedText: '已选择',
                allSelectedText: '已选择全部',
                buttonWidth: '100%',
                buttonText: function(options, select) {
                    // console.log(options.length, select);

                    if (options.length === 0) {
                        return '请选择公司';
                    } else {
                        return '已选择' + options.length + '个公司';
                    }
                },
                onChange: function () {

                },
                onSelectAll: function () {
                    return '已选择全部'
                },
                onDeselectAll: function () {

                }
            });
        }
    });
}

function getCompanyTax() {


    $.ajax({
    // /sysInvoiceCompany/selectInvoiceCompanyList   /sysCompany/selectCompanyAndTaxNumberList
        url: "/sysInvoiceCompany/selectInvoiceCompanyList",
        type:"post",
        dataType: 'json',
        async:false,
        // contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            var data = data.data;

            var productListHtml = '';
            for (var i = 0; i < data.length; i++) {
                productListHtml += '<option value="' + data[i].companyId + '">' + data[i].companyName+'-'+ data[i].taxNumber + '</option>'
            }

            //$('#productList').html('<option value="1">全部产品</option>' + productListHtml).selectpicker('refresh');
            $('#useCompanyId2').html(productListHtml).multiselect("destroy").multiselect({
                filterPlaceholder: '搜索',
                enableFiltering: true,
                includeSelectAllOption: false,
                maxHeight: 300,
                selectAllText: '全部选择',
                nonSelectedText: '请选择',
                nSelectedText: '已选择',
                allSelectedText: '已选择全部',
                buttonWidth: '100%',
                buttonText: function(options, select) {
                    if (options.length === 0) {
                        return '请选择公司';
                    } else {
                        return '已选择' + options.length + '个公司';
                    }
                },
                onChange: function () {

                },
                onSelectAll: function () {
                    return '已选择全部'
                },
                onDeselectAll: function () {

                }
            });

        },
        error: function (err) {
            console.log(err);
        }
    })
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" data-toggle="collapse" data-target="#updateTaxDisc" aria-expanded="false" aria-controls="updateTaxDisc" ' +
        'onclick="updateTaxDisc(\''+row.companyId+'\',\''+row.companyName+'\',\''+row.taxNumber+'\',\''+row.useCompanyIds+'\')">修改税盘</button>';
    html += '<button class="btn btn-default" ' +
        'onclick="delTaxDisc(\''+row.companyId+'\')">删除</button>';

    html += '</ul></div>'
    return html;
}

//回显
function updateTaxDisc(companyId,companyName,taxNumber,useTaxNumbers) {
    $("#companyName2").val(companyName);
    $("#taxNumber2").val(taxNumber);
    $("#companyIdHide").val(companyId);
    let arr = useTaxNumbers.split(',')
    $('#useCompanyId2').multiselect('select', arr);


}

//删除税盘
function delTaxDisc(companyId) {
    $.alert({
        title: '提示',
        content: "确定要删除吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/companyInvoice/delTaxDisc",
                        data: {
                            companyId: companyId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('操作成功!');
                                $taxDiscFromTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('删除失败，请稍后再试!');
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

//修改税盘
function subUpdateTaxDisc() {
    var useCompanyIds = [];
    var companyId = $("#companyIdHide").val();
    var taxNumber = $("#taxNumber2").val();
    useCompanyIds = $("#useCompanyId2").val();
    var jsonData = {
        "companyId":companyId,
        "taxNumber":taxNumber,
        "useCompanyIds":useCompanyIds
    }
    $.ajax({
        url: '/companyInvoice/updateTaxDisc',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '操作成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}

//添加税盘
function addTaxDisc() {
    // 赠品
    var useCompanyIds = [];
    var companyId = $("#searchCompanySelect").val();
    var taxNumber = $("#taxNumber").val();
    useCompanyIds = $("#useCompanyId").val();
    var jsonData = {
        "companyId":companyId,
        "taxNumber":taxNumber,
        "useCompanyIds":useCompanyIds
    }
    $.ajax({
        url: '/companyInvoice/saveTaxDisc',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '操作成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
                            }
                        }
                    }
                });
            } else {
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}

function clearAllData() {
    window.location.reload();
}

//
// function getGiftInfo() {
//     var editGiftId = $('#editGiftId').val();
//     $.ajax({
//         url: "/customerGiftActivityRelation/selectGiftDropDownCheckedListByGiftActivityId?giftActivityId=" + editGiftId,
//         type: "get",
//         dataType: 'json',
//         contentType: "application/x-www-form-urlencoded",
//         success: function (data) {
//             // console.log(data)
//             var data = data.data;
//
//             // 初始化选中项数组
//             var giftArr = [];
//
//             for (var i = 0; i < data.length; i++) {
//                 if (data[i].checked) {
//                     giftArr.push(data[i].productId);
//                 }
//             }
//             // 反显选中条目
//             $('#useCompanyId2').multiselect('select', giftArr);
//         },
//         error: function (err) {
//             console.log(err);
//         }
//     })
// }

function getCompanyTaxNumber(companyId) {
    $.ajax({
        url: "/sysCompany/selectCompanyTaxNumber?companyId="+companyId,
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            var data = data.data;
            $("#taxNumber").val(data);
        },
        error: function (err) {
            console.log(err);
        }
    })
}

